package com.zwh.se.fileEncrypt;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件加密
 */
public class FileEncrypt {
    public static void main(String[] args) throws IOException {
        // 需要加密/解密的文件路径
        String inputPath = "D:\\idea\\file\\test.csv";
        // 加密/解密后的文件路径
        String outPath = "D:\\idea\\file\\test1.csv";

        // 用于存储文件字节码的集合数组
        List<Byte> byteList = new ArrayList<>();

        // 秘钥
        Byte key = 17;

        // 读取文件
        readFile(inputPath, byteList);
        // 加密/解密
        encryption(byteList, key);
        // 生成加密/解密后的文件
        writeText(byteList, outPath);

    }

    /**
     * 读取文件
     *
     * @param inputPath 文件输入路径
     * @param byteList  文件的字节码列表
     * @throws IOException
     */
    public static void readFile(String inputPath, List<Byte> byteList) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputPath));
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            for (int i = 0; i < len; i++) {
                byteList.add(bytes[i]);
            }
        }
        bis.close();
    }

    /**
     * 加密/解密
     *
     * @param byteList
     * @param key
     */
    public static void encryption(List<Byte> byteList, byte key) {
        for (int i = 0; i < byteList.size(); i++) {
            Byte aByte = byteList.get(i);
            // 把集合中的字节码与秘钥或运算
            Byte enNum = (byte) (aByte ^ key);
            // 把加密后的数替换原集合中的数
            byteList.set(i, enNum);
        }
    }

    /**
     * 生成加密/解密后的文件
     *
     * @param byteList
     * @param outPath
     * @throws IOException
     */
    public static void writeText(List<Byte> byteList, String outPath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
        byte[] tempByte = new byte[byteList.size()];
        for (int i = 0; i < byteList.size(); i++) {
            tempByte[i] = byteList.get(i);
        }
        bos.write(tempByte);
        bos.close();
    }
}

